package com.dwxt.cdms.service;

import com.dwxt.cdms.admin.service.UserServiceAdmin;
import com.dwxt.cdms.dao.EquipmentMapper;
import com.dwxt.cdms.dao.StationMapper;
import com.dwxt.cdms.entity.Equipment;
import com.dwxt.cdms.exception.CustomException;
import com.dwxt.cdms.util.LbWatchCodeTool;
import com.dwxt.cdms.vo.SelectEquipmentVo;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.constant.VariableConstants;
import com.dwxt.common.util.SnowIdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 设备管理
 *
 * @author Kuang.JiaZhuo
 * @date 2020-09-04 17:45
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class EquipmentService {

    private final EquipmentMapper equipmentMapper;
    private final UserServiceAdmin userServiceAdmin;
    private final StationMapper stationMapper;
    private final StationService stationService;
    private final LbWatchService lbWatchService;

    /**
     * @方法名：createOrUpdateEquipment
     * @描述： 新增或修改设备档案
     * @作者： kjz
     * @日期： Created in 2020/9/4 17:53
     */
    @Transactional(rollbackFor = Exception.class)
    public Equipment createOrUpdateEquipment(Equipment equipment) {
        String id = equipment.getId();


        String serialNumber = equipment.getSerialNumber();
        if (null == serialNumber || serialNumber.trim().length() == 0) {
            throw new CustomException(StatusCode.SERIAL_NUMBER_NOT_NULL);
        }

        if (null == id || id.trim().length() == 0) {
            /** 新增*/

            //处理来邦序列号
            if (equipment.getCategory().equals("12")&&equipment.getSerialNumber().length()>17) {
                serialNumber = LbWatchCodeTool.parse(equipment.getSerialNumber().trim()).getMac();
            }

            //设备序列号不能重复
            boolean isRepeat = judgeEquipmentIsRepeat(serialNumber, null);
            if (isRepeat) {
                throw new CustomException(StatusCode.SERIAL_NUMBER_IS_REPEAT);
            }

            //来邦手表注册绑定
            if (equipment.getCategory().equals("12")&&equipment.getSerialNumber().length()>17) {
                LbWatchCodeTool parse = LbWatchCodeTool.parse(equipment.getSerialNumber().trim());
                //在来邦服务器注册绑定老人
                String lbUserid = lbWatchService.addElder(equipment.getSerialNumber());
                if ("error".equals(lbUserid)) {
                    throw new CustomException(StatusCode.LB_ADD_ERROR);
                }
                equipment.setSerialNumber(parse.getMac());
                equipment.setLbUserid(lbUserid);
            }

            equipment.setId(SnowIdUtil.getInstance().nextId())
                    .setCreateTime(LocalDateTime.now())
                    .setType(VariableConstants.STRING_CONSTANT_0)
                    .setIsDelete(VariableConstants.STRING_CONSTANT_0)
                    .setIsEnabled(VariableConstants.STRING_CONSTANT_1);
            equipmentMapper.insert(equipment);
        } else {
            /** 更新*/
            Equipment oldEquipment = this.equipmentMapper.selectEquipmentById(id);
            //设备如果发送，序列号不能改
            if (null != oldEquipment && oldEquipment.getType().equals(VariableConstants.STRING_CONSTANT_1)) {
                if (!equipment.getSerialNumber().equals(oldEquipment.getSerialNumber())) {
                    throw new CustomException(StatusCode.SERIALNUMBER_NOT_CHANGE);
                }
            }
            //设备序列号不能重复
            boolean isRepeat = judgeEquipmentIsRepeat(serialNumber, id);
            if (isRepeat) {
                throw new CustomException(StatusCode.SERIAL_NUMBER_IS_REPEAT);
            }

            equipmentMapper.updateByPrimaryKeySelective(equipment);
        }
        return equipment;
    }

    /**
     * @方法名：judgeEquipmentIsRepeat
     * @描述： 根据【设备序列号】判断设备是否重复
     * @作者： kjz
     * @日期： Created in 2020/9/16 16:40
     */
    public boolean judgeEquipmentIsRepeat(String serialNumber, String id) {
        Equipment equipment = this.equipmentMapper.selectEquipmentBySerialNumber(serialNumber, id);
        if (null != equipment) {
            return true;
        }
        return false;
    }

    /**
     * @方法名：pageEquipmentList
     * @描述： 按条件查询设备列表(带分页)
     * @作者： kjz
     * @日期： Created in 2020/9/5 14:04
     */
    public PageInfo<Equipment> pageEquipmentList(SelectEquipmentVo selectVo) {
        Integer stationId = stationService.getLoginUserStation();
        PageHelper.startPage(selectVo.getPageNum(), selectVo.getPageSize());
        if (stationId != null) {
            selectVo.setStationId(stationId);
        }
        List<Equipment> adminUserVos = equipmentMapper.pageEquipmentList(selectVo);
        PageInfo<Equipment> pageInfo = new PageInfo(adminUserVos);
        return pageInfo;
    }

    /**
     * @方法名：deleteDataByIds
     * @描述： 根据ids批量删除设备数据
     * @作者： kjz
     * @日期： Created in 2020/9/5 14:52
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteDataByIds(String[] ids) {
        if (null == ids || ids.length == 0) {
            throw new CustomException(StatusCode.ID_IS_NULL);
        }

        //已经发放的设备不能删除
        for (String id : ids) {
            Equipment equipment = this.selectEquipmentById(id);
            if (null != equipment) {
                String distributionStatus = equipment.getType();
                if (distributionStatus.equals(VariableConstants.STRING_CONSTANT_1)) {
                    throw new CustomException(StatusCode.EQUIPMENT_NOT_DELETE);
                }
            }
        }

        int result = equipmentMapper.deleteEquipmentByIds(ids);
        //删除其他关联


        return result;
    }

    /**
     * @方法名：selectEquipmentById
     * @描述： 根据id查询设备详情
     * @作者： kjz
     * @日期： Created in 2020/9/5 15:17
     */
    public Equipment selectEquipmentById(String id) {
        Equipment equipment = equipmentMapper.selectEquipmentById(id);
        return equipment;
    }

    public List<Equipment> selectEquipmentByCategory(int category) {
        Example example = new Example(Equipment.class);
        example.createCriteria().andEqualTo("category", category).andEqualTo("isEnabled",1);
        return equipmentMapper.selectByExample(example);
    }


    public Equipment selectEquipmentByLbUserId(String lbUserId) {
        Equipment eqParam = new Equipment();
        eqParam.setLbUserid(lbUserId);
        Equipment equipment = equipmentMapper.selectOne(eqParam);
        return equipment;
    }

    public Equipment selectEquipmentBySerialNumber(String serialNumber) {
        return equipmentMapper.selectEquipmentBySerialNumber(serialNumber, null);
    }
}
